package com.leyou.user.interceptors;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 处理器拦截器
 */
@Slf4j
@Component
public class PrivilegeInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        try {
            //获取token
            String token = request.getHeader(jwtProperties.getApp().getHeaderName());
            //校验token
            Payload<AppInfo> payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), AppInfo.class);
            AppInfo appInfo = payload.getUserInfo();
            List<Long> targetList = appInfo.getTargetList();
            //获取本地服务的id
            Long id = jwtProperties.getApp().getId();
            //判断是否有目标服务是否包含本服务
            if(targetList == null || !targetList.contains(id)){
                log.error("请求者没有访问本服务的权限！");
                return false;
            }
            log.info("服务{}正在请求资源:{}", appInfo.getServiceName(), request.getRequestURI());
            return true;
        } catch (Exception e) {
            log.error("服务访问被拒绝，token认证失败!",e);
            return false;
        }
    }
}
